<?php

namespace App\Admin\Controllers;

use App\Http\Controllers\Controller;

use Encore\Admin\Controllers\HasResourceActions;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Show;
use Encore\Admin\Facades\Admin;
use App\Admin\Models\DistributionBill;
use App\Admin\Models\Common;
use Illuminate\Support\Facades\Input;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;
use Ixudra\Curl\Facades\Curl;

class DistributionBillController extends Controller
{
	use HasResourceActions;
	
    /**
     * Index interface.
     *
     * @param Content $content
     * @return Content
     */
    public function index(Content $content)
    {
        return $content
            ->header('分销')
            ->description('列表')
            ->body($this->grid());
    }

    /**
     * Show interface.
     *
     * @param mixed $id
     * @param Content $content
     * @return Content
     */
    public function show($id, Content $content)
    {
        return $content
            ->header('分销')
            ->description('详细')
            ->body($this->detail($id));
    }

    /**
     * Edit interface.
     *
     * @param mixed $id
     * @param Content $content
     * @return Content
     */
    public function edit($id, Content $content)
    {
        return $content
            ->header('分销')
            ->description('编辑')
            ->body($this->form()->edit($id));
    }

    /**
     * Create interface.
     *
     * @param Content $content
     * @return Content
     */
    public function create(Content $content)
    {
        return $content
            ->header('分销')
            ->description('创建')
            ->body($this->form());
    }
    
//  public function update(Request $request, $id)
//  {
//
//  }
    
//  /**
//   * Handle update.
//   *
//   * @param int $id
//   *
//   * @return \Symfony\Component\HttpFoundation\Response
//   */
//  public function update($id, $data = null)
//  {	
//  	
//      return $this->returnMsg(1, $id);
//  }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        $grid = new Grid(new DistributionBill);

        $grid->dbId('ID');
        $grid->dbObjName('分销商品');
        $grid->dbSaleNum('商品数量');
        $grid->dbSaleMoney('分销金额')->display(function ($email) {
        	if ($this->dbActualMoney && $this->dbActualMoney != $this->dbSaleMoney){
        		return $this->dbSaleMoney."(实际支付：{$this->dbActualMoney})";
        	}else{
        		return $this->dbSaleMoney;
        	}
		});
        $grid->userName0('购买人')->display(function ($email) {
		    return $this->userName0."【{$this->alName0}】";
		});
        $grid->userName1('推荐人')->display(function ($email) {
		    return $this->userName1."【{$this->alName1}】";
		});
        $grid->dbSelfMoney('返利');
		$grid->userName2('推荐人上级')->display(function ($email) {
		    return $this->userName2."【{$this->alName2}】";
		});
        $grid->dbParentMoney('上级返利');
        $grid->userName3('推荐人上上级')->display(function ($email) {
		    return $this->userName3."【{$this->alName3}】";
		});
        $grid->dbGrandMoney('上上级返利');
        $grid->createTime('分销时间');

		$grid->filter(function($filter){

		    // 去掉默认的id过滤器
		    $filter->disableIdFilter();

		});
		
		$grid->actions(function ($actions) {
		    $actions->disableDelete();
		    $actions->disableEdit();
		    $actions->disableView();
		    
		    if ($actions->row->dbIsCancel == 1){
		    	$dbId = $actions->row->dbId;
		    	$actions->append('<lable class="font-size">出库单取消分销无效</lable>');
		    	$actions->append('<input type="hidden" id="sign'.$dbId.'">');
		    	$grayScript = <<<EOT

	$('#sign{$dbId}').parent().parent().css({"background": "#CCCCCC"});

EOT;
				Admin::script($grayScript);
		    }
		});

		$grid->filter(function($filter){

		    // 去掉默认的id过滤器
		    $filter->disableIdFilter();

            $filter->like('muRealName', '姓名');
            $filter->like('muMobile', '手机号');
            $formartData = array();
            $formartData[0] = '女';
            $formartData[1] = '男';

            $filter->equal('muSex', '性别')->select($formartData);
		    
//		    $filter->column(1/2, function ($filter) {
//
//		    	$filter->like('muRealName', '姓名');
//		    	$filter->like('muMobile', '手机号');
//			    $formartData = array();
//		    	$formartData[0] = '女';
//		    	$formartData[1] = '男';
//
//			    $filter->equal('muSex', '性别')->select($formartData);
//			});
//
//			$filter->column(1/2, function ($filter) {
//				//$filter->equal('muAccount', '店名');
//				$filter->gt('muAccount', '账户余额');
//				$filter->gt('muPoints', '积分');
//			    $filter->gt('muTotalExpend', '总消费');
//			});

		});

		// 默认展开筛选框
//		$grid->expandFilter();
		
		// 禁用行选择checkbox
		$grid->disableRowSelector();
		
		// 禁用创建按钮
		$grid->disableCreateButton();
		
		// 禁用导出
		$grid->disableExport();
        return $grid;
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     * @return Show
     */
    protected function detail($id)
    {
    	$Member = new Member();
        $show = new Show($Member->findOrFail($id));

        $show->muId('ID');
        $show->muCode('用户码');
        $show->muNickName('昵称');
        $show->muRealName('姓名');
        $show->muSex('性别')->using(['0' => '女', '1' => '男']);;
        $show->muMobile('手机号');
        $show->muMemo('备注');
//      $show->muAccount('账户金额');
        $show->muPoints('积分');
        $show->muTotalExpend('总消费');
        $show->createTime('创建时间');
        $show->updateUser('最后修改人');
        $show->updateTime('最后修改时间');

        return $show;
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {


        return Admin::Form(Member::class, function (Form $form) {
			
			$form->hidden('muId');
			$form->text('muNickName', '昵称');
			$form->text('muRealName', '姓名');
            $form->text('muCardNum', '卡号');
			$form->radio('muSex', '性别')->options(['0' => '女', '1'=> '男'])->default(0);
            $form->date('muBirthday', '生日');
            //A、B、AB和O血型之外,还有Rh阳性、Rh阴性
            $form->select('muBloodType', '血型')
                ->options(['A'=>'A','B'=>'B','AB'=>'AB','O'=>'O','Rh阳'=>'Rh阳','Rh阴'=>'Rh阴']);
			$form->mobile('muMobile', '电话')->rules('required|regex:/^[1][0-9]{10}$/', [
        									'required' => '请填写手机号',
        									'regex' => '手机号格式不正确'
        									])
        									->attribute(['style' => 'width: 25%']);
            $form->text('muAddress', '地址');
        	$form->select('alId', '身份')->options($this->getAgencyLevelSelect());
        	$form->textarea('muMemo', '备注');
//      	$form->number('mlId', '等级');
        	$form->select('muReferrerId', '推荐人')->options($this->getReferrerSelect());
			$form->hidden('muCode')->default($this->create_guid());

            $form->tools(function (Form\Tools $tools) {

			    // 去掉`列表`按钮
//			    $tools->disableList();
				
			    // 去掉`删除`按钮
			    $tools->disableDelete();
			
			    // 去掉`查看`按钮
//			    $tools->disableView();
			
			    // 添加一个按钮, 参数可以是字符串, 或者实现了Renderable或Htmlable接口的对象实例
//			    $tools->add('<a class="btn btn-sm btn-danger"><i class="fa fa-trash"></i>&nbsp;&nbsp;delete</a>');
			});
			
			$form->footer(function ($footer) {

//			    // 去掉`重置`按钮
//			    $footer->disableReset();
//			
//			    // 去掉`提交`按钮
//			    $footer->disableSubmit();
			
			    // 去掉`查看`checkbox
			    $footer->disableViewCheck();
			
			    // 去掉`继续编辑`checkbox
			    $footer->disableEditingCheck();
			
			    // 去掉`继续创建`checkbox
//			    $footer->disableCreatingCheck();
			
			});
			
			//保存后回调
			$form->saved(function (Form $form) {
				if (!$form->model()->muId){
					$sId = Admin::user()->sId;
					$username = Admin::user()->name;
					$host = config('admin.dataApiHost');
					$url = $host.'/distributionUsers/boundRelation';
					$data = array();
					$data['dcKey'] = $sId;
					$data['uId'] = $form->model()->muCode;
					$data['parentId'] = $form->model()->muReferrerId;
					$data['operationUser'] = $username;

					$response = Curl::to($url)
						->withData($data)
						->post();
				}			    
			});
        });
    }
    
    // 获取区域列表下拉框数据
    public function getAreaSelectData($parentCode=''){

		if (isset($_GET['q'])){
			$parentCode = $_GET['q'];
		}
    	$Common = new Common();
    	$baseData = $Common->getAreaList($parentCode);
    	
    	if (isset($_GET['q'])){
    		return $baseData;
    	}
    	$selectData = array();
    	foreach($baseData as $info){
    		$selectData[$info['areaCode']] = $info['areaName'];
    	}
    	
    	return $selectData;
    }
    
    private function getAgencyLevelSelect(){
		
		$sId = Admin::user()->sId;
		$host = config('admin.dataApiHost');
		$url = $host.'/agencyLevel/getList?acKey='.$sId;

		$data = Curl::to($url)->get();

		$data = json_decode($data, true);
		$infoList = $data['data']['data'];
		
		$selectData = array();
		foreach($infoList as $info){
			$selectData[$info['alId']] = $info['alName'];
		}
		
		return $selectData;
	}
	
	private function getReferrerSelect(){
		
		$userModel = config('admin.database.users_model');

		$sId = Admin::user()->sId;

        $userM = new $userModel();
		$userList = $userM->where('sId', $sId)->get();
		
		$selectData = array();
		foreach($userList as $info){
			$selectData[$info['auCode']] = $info['name'];
		}

        $host = config('admin.dataApiHost');
        $sId = Admin::user()->sId;
        $url = $host . "/member/getList?mcKey={$sId}&page=1&perPage=1000";
        $rst = Curl::to($url)->get();
        $user = json_decode($rst, true);
        if(!empty($user['data']['data'])){
            $list = $user['data']['data'];
            foreach($list as $info){
                $selectData[$info['muCode']] = $info['muRealName'];
            }
        }
		
		return $selectData;
	}
	
	private function create_guid() {
		$charid = md5(uniqid(mt_rand(), true));
		$hyphen = chr(45);// "-"
		$uuid = substr($charid, 0, 8)
				.substr($charid, 8, 4)
				.substr($charid,12, 4)
				.substr($charid,16, 4)
				.substr($charid,20,12);
		return $uuid;
	}
}
